<template>
  <div>
    <h2>用户投资页面</h2>
    <table class="table table-bordered">
      <tr>
        <td align="right">项目名称：</td>
        <td>{{  state.I_Name }}</td>
      </tr>
      <tr>
        <td align="right">投资总金额：</td>
        <td>{{  state.I_Budget }}</td>
      </tr>
      <tr>
        <td align="right">已投金额：</td>
        <td>{{  state.I_Receive }}</td>
      </tr>
      <tr>
        <td align="right">剩余金额：</td>
        <td>{{  state.I_Residue }}</td>
      </tr>
      <tr>
        <td align="right">投资金额：</td>
        <td>
          <input type="text" v-model="UIMoney">
        </td>
      </tr>
      <tr v-if="UIMoney!=''">
        <td align="right">预期最高收益：</td>
        <td>{{ maxMoney }}</td>
      </tr>
      <tr>
        <td align="right"></td>
        <td>
          <input type="button" value="确认投资" @click="ok"/>
        </td>
      </tr>
    </table>
  </div>
</template>

<script setup lang="ts">
//watch监听的意思
import {reactive,toRefs,onMounted,ref,watch} from 'vue'
import axios from 'axios';
import {useRoute,useRouter} from 'vue-router'
import { useUserStore } from '../../store/user'


const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

let UIMoney = ref('');
let data:any = reactive({
  state:{},
  maxMoney:''
})

let {state,maxMoney} = toRefs(data)

onMounted(()=>{
  getData()
})

//UIMoney这个数据，一旦变化会自动调用watch
watch(UIMoney,(newVal,oldVal)=>{
  maxMoney.value = (Number(newVal)*0.06).toFixed(2) + ' CNF'
})




//函数--------------------------------------
//点击确认投资
const ok = ()=>{
    //1.验证投资金额不能为空，投资金额必须是数字， 投资金额必须小于总金额
    if(UIMoney.value == ""){
      alert("用户投资金额不能为空");
      return
    }
    if(isNaN(Number(UIMoney.value)) == true){
      alert("投资金额必须是数字");
      return
    }

    if(UIMoney.value > state.value.I_Residue){
      alert("投资金额必须小于剩余金额");
      return
    }
    //2.发送网络请求将用户投资金额及用户信息进行存储
    //1.需要创建一个实体类存储用户投资信息（U_Id,I_Id,UIMoney,UI-Date）
    //2.前端需要向后端传递这些数据
    axios({
      url:'/api/Invest/PostAddUserInvest',
      method:'post',
      data:{
        U_Id:userStore.userInfo.U_Id,   //用户投资Id
        I_Id:route.query.id,
        UI_Money:UIMoney.value
      }
    })
    .then(res=>{
      console.log(res);
      if(res.data.data>0){
        alert("投资成功");
        router.push("/main/userInvestList")
      }else if(res.data.data == -1){
        alert("投资金额要小天剩余金额");
        return;
      }else{
        alert("投资失败")
        return
      }
      
    }).
    catch(err=>{
      console.log(err);
      
    })
}

//页面一进来就要根据投资的ID进行请求数据
const getData = ()=>{
  axios({
    url:'/api/Invest/GetInvestItem',
    method:'get',
    params:{
      Iid:route.query.id
    }
  })
  .then(res=>{
    console.log(res);
    state.value = res.data.data
  })
  .catch(err=>{
    console.log(err);
    
  })
}



</script>

<style scoped>

</style>